package com.lepu.app.fun.mother_circle;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.app.application.MyApplication;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.core.lib.widget.GoogleRefreshLayout;
import com.core.lib.widget.GoogleRefreshLayout.OnLoadListener;
import com.eyzhs.app.R;
import com.lepu.app.fun.mother_circle.adapter.AdapterMotherPost;
import com.lepu.app.fun.my.bean.BeanPubContent;
import com.lepu.app.usercenter.bean.LoginInfo;

public class MotherPostSearchActivity extends BaseFragmentActivity implements AsyncRequest, 
    OnRefreshListener, OnLoadListener, OnEditorActionListener{

	private static final String REQUEST_DATA = "request_data";
	private static final String REQUEST_DATA_MORE = "request_data_more";

	private static final int MSG_DATA_SUCCESS = 10;
	private static final int MSG_DATA_FAIL = 11;
	private static final int MSG_DATA_MORE_SUCCESS = 12;
	private static final int MSG_DATA_MORE_FAIL = 13;
	
	private GoogleRefreshLayout mGoogleRefreshLayout = null;
	private ListView mListView;
	private AdapterMotherPost mDataAdapter = null;
	public ArrayList<BeanPubContent> mDataList = null;
	
	private EditText mMontentEditText;
	private String mSearchWord;
	
	private int mCurrentPage = 1;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mother_post_search_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}

	private void showHideNoDataLayout(boolean isShow)
	{
		LinearLayout noDataLayout = (LinearLayout) findViewById(R.id.noDataLayout);
		if(noDataLayout != null)
		{
			if(isShow)
			{
				noDataLayout.setVisibility(View.VISIBLE);
				mListView.setVisibility(View.GONE);
			}else{
				noDataLayout.setVisibility(View.GONE);
				mListView.setVisibility(View.VISIBLE);
			}
		}
	}
	
	/**
	 * 初始化方法
	 */
	@SuppressWarnings("deprecation")
	private void init() {
		mListView = (ListView) findViewById(R.id.dataListView);
		mGoogleRefreshLayout = (GoogleRefreshLayout)findViewById(R.id.swipeLayout);
		mGoogleRefreshLayout.setOnRefreshListener(this);
		mGoogleRefreshLayout.setOnLoadListener(this);
		mGoogleRefreshLayout.setColorScheme(R.color.color_listview_refresh_1,
				                            R.color.color_listview_refresh_2,
				                            R.color.color_listview_refresh_3,
				                            R.color.color_listview_refresh_4);
		
		// back
		LinearLayout backLayout = (LinearLayout) findViewById(R.id.backLayout);
		backLayout.setOnClickListener(mOnClickListener);
		
		mMontentEditText = (EditText) findViewById(R.id.contentEditText);
		mMontentEditText.setOnEditorActionListener(this);
		mMontentEditText.setFilters(new InputFilter[]{new EmojiFilter(),new InputFilter.LengthFilter(30)});
	}
	
	private View.OnClickListener mOnClickListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			int rid = v.getId();
			switch (rid) {
			case R.id.backLayout:
				finish(true);
				break;

			default:
				break;
			}
		}
	};
	
	//请求数据
	public void request(boolean isMore) {
        
		String request = "";
		int page = 1;
		if (isMore) {
			request = REQUEST_DATA_MORE;
			page = (mCurrentPage + 1);
		} else {
			request = REQUEST_DATA;
			mCurrentPage = page;
		}

		String url = Setting.getSearchListUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			if (MyApplication.getInstance().checkIsLogin()) {
				LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
				params.put("UserID", loginInfo.UserID);
			} else {
				params.put("UserID", -1);
			}

			params.put("RefreshTime", DateUtilBase.stringFromDate(new Date(),DateUtilBase.DATE_ALL_ALL));
			params.put("PageIndex", page);
			params.put("PageSize", Setting.PAGE_SIZE);
			params.put("Keywords", mSearchWord);
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post(url, map, null, this, request, true,false,true);
	}

	
	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {

		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case MSG_DATA_SUCCESS:

				ArrayList<BeanPubContent> dataList = (ArrayList<BeanPubContent>) msg.obj;
				if (dataList != null && dataList.size() > 0) {

					mDataList = dataList;
					
					showHideNoDataLayout(false);
				} else {
					UIHelper.showToast(MotherPostSearchActivity.this, R.string.no_data);

					showHideNoDataLayout(true);
				}

				if (mDataList == null) {
					mDataList = new ArrayList<BeanPubContent>();
				}

				mDataAdapter = new AdapterMotherPost(MotherPostSearchActivity.this,mDataList);
				
				ImageView tempImageView = new ImageView(MotherPostSearchActivity.this);
				mListView.addHeaderView(tempImageView);
				mListView.setAdapter(mDataAdapter);
                mListView.removeHeaderView(tempImageView);
				
				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				
				mMontentEditText.clearFocus();
				UtilityBase.closeSoftInput(MotherPostSearchActivity.this);
				
				break;
			case MSG_DATA_FAIL:

				// 更新完后调用该方法结束刷新
				mGoogleRefreshLayout.setRefreshing(false);
				
				showHideNoDataLayout(true);
				
				mMontentEditText.clearFocus();
				UtilityBase.closeSoftInput(MotherPostSearchActivity.this);
				break;
			case MSG_DATA_MORE_SUCCESS:

				ArrayList<BeanPubContent> dataMoreList = (ArrayList<BeanPubContent>) msg.obj;
				if (dataMoreList != null && dataMoreList.size() > 0) {
					mDataAdapter.notifyDataSetChanged();

					// 加载更多数据成功，page ++
					mCurrentPage++;
				} else {
					UIHelper.showToast(MotherPostSearchActivity.this, R.string.no_data_more);
				}

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			case MSG_DATA_MORE_FAIL:

				// 加载完后调用该方法
				mGoogleRefreshLayout.setLoading(false);
				break;
			default:
				break;
			}
		};
	};
	
	@Override
	public void onLoad() {
		request(true);
	}

	@Override
	public void onRefresh() {
		request(false);
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		if (object.equals(REQUEST_DATA)) {
			// 解析json data
			ArrayList<BeanPubContent> dataArraylist = BeanPubContent.parseJsonData((String) data);

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_SUCCESS;
			msg.obj = dataArraylist;
			mHandler.sendMessage(msg);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			// 解析json data more
			ArrayList<BeanPubContent> dataMoreArraylist = BeanPubContent.parseJsonData((String) data);

			if (dataMoreArraylist != null && dataMoreArraylist.size() > 0) {
				for (int i = 0; i < dataMoreArraylist.size(); i++) {
					mDataList.add(dataMoreArraylist.get(i));
				}
			}

			Message msg = mHandler.obtainMessage();
			msg.what = MSG_DATA_MORE_SUCCESS;
			msg.obj = dataMoreArraylist;
			mHandler.sendMessage(msg);
		} 
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_DATA)) {
			mHandler.sendEmptyMessage(MSG_DATA_FAIL);
		} else if (object.equals(REQUEST_DATA_MORE)) {
			mHandler.sendEmptyMessage(MSG_DATA_MORE_FAIL);
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
		case EditorInfo.IME_ACTION_SEARCH:
			
			String searchWord = mMontentEditText.getText().toString().trim();
			if(TextUtils.isEmpty(searchWord)){
				UIHelper.showToast(MotherPostSearchActivity.this, "请输入搜索关键字");
				return true;
			}
			
			mSearchWord = searchWord;
			
			mGoogleRefreshLayout.setRefreshing(true);
			request(false);
			
			break;
		}
		return true;
	}
}
